package com.blackhorse.controller;

import com.alibaba.fastjson.JSON;
import com.blackhorse.domain.Order;
import com.blackhorse.domain.Product;
import com.blackhorse.service.ProductService;
import com.blackhorse.service.impl.OrderServiceImpl4;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 测试rocektmq事务消息的controller
 * 使用时打开RestController注解
 */
@Slf4j
//@RestController
public class OrderController4 {

    /**
     * 可直接注入Feign的远程调用接口
     */
    @Autowired
    private ProductService productService;
    @Autowired
    private OrderServiceImpl4 orderService;

    /**
     * 用户下单接口
     */
    @RequestMapping("/order/prod/{pid}")
    public Order order(@PathVariable("pid") Integer pid) {
        log.info("订单微服务-下单-开始 pid:{}", pid);
        Product product = productService.findByPid(pid);
        log.info("订单微服务-下单-查询到商品信息 pid:{} product:{}", pid, JSON.toJSONString(product));

        if (product == null) {
            throw new IllegalArgumentException("商品不存在");
        }

        //判断是否走容错逻辑，测试时直接停掉商品微服务即可模拟
        if (product.getPid() == -100) {
            Order order = new Order();
            order.setOid(-100);
            order.setPname("下单失败");
            return order;
        }

        Order order = new Order();
        order.setUid(1);
        order.setUsername("测试用户");
        order.setPid(pid);
        order.setPname(product.getPname());
        order.setPprice(product.getPprice());
        order.setNumber(1);
        //发送半事务消息，同时利用RocketMQLocalTransactionListener执行本地事务
        orderService.createOrderBefore(order);

        log.info("订单微服务-下单-创建订单成功 order:{}", JSON.toJSONString(order));

        //已有事务消息，代替生产下单成功MQ
//        rocketMQTemplate.convertAndSend("order-topic", order);
        return order;
    }
}
